/**
 * Created by TomSean on 2017/3/19.
 */
var PreferentialInfoList = function($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
}
PreferentialInfoList.prototype = {
    init : function() {
        var fieldArray = this.sysUtils.getBindFieldArray(this.$parent.find('.search-panel'))
        var functionArray = [
            {fName : "search_btn", fs : this.findData},
            {fName : "reset_btn", fs : this.resetInfo}
        ];
        this.bindBaseModels = new bindBaseModel(null, fieldArray, functionArray, null);
        this.sysUtils.bindDoucment(this.bindBaseModels, this.$parent, this);
        Utils.createDataDictDropDownList({div : this.$parent.find('#preferentialType'), parentModelKey : BASIS.PREFERENTIAL_TYPE.ROOT}, this);
        Utils.createDataDictDropDownList({div : this.$parent.find('#preferentialObject'), parentModelKey : BASIS.PREFERENTIAL_OBJECT.ROOT}, this);
        this.createList();
        this.findData();
    },
    /*
     * 重置按钮
     */
    resetInfo:function(e){
        var that = $(e.target).data("that");
        that.sysUtils.setBindFieldNull(that.bindBaseModels.bindFieldArray);
    },
    newData : function (e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        _this.isEdit = true;
        _this.entity = undefined;
        _this.editWindow = _this.sysUtils.openWindow(_this.editWindow, {
            title : "新增优惠项目",
            height : "375px",
            width : "675px",
            resizable : false,
            content : "views/parkLotCenter/discountManage/preferential_edit.html"
        });
    },
    editData : function(e) {
        var _this = this;
        _this.isEdit = true;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        var id = _this.selectRowId;
        if ( !id || id == undefined ){
            notification({title : "操作失败", message : "请先选择需要修改哪一行数据"}, 'info')
            return;
        }
        JsonpAjax(baseApiPath + "preferential/one/" + id, undefined, "json", function(res) {
            _this.entity = res;
            _this.editWindow = _this.sysUtils.openWindow(_this.editWindow, {
                title : "修改优惠项目",
                height : "375px",
                width : "675px",
                resizable : false,
                content : "views/parkLotCenter/discountManage/preferential_edit.html"
            });
        });

    },
    deleteData : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        var ids = "";
        _this.$parent.find("input[name='preferentialCode']:checked").each(function(inx, itm) {
            ids += $(itm).val() + ',';
        });
        if (ids == '' || ids.length < 1) {
            notification({title : "操作失败", message : "请至少选择一行需要删除的数据"}, 'info');
            return;
        }
        ids = ids.substring(0, ids.length - 1);
        var dataT = {ids : ids};
        JsonpAjax(baseApiPath + "preferential/delete", dataT, "json", function(res) {
            _this.findData();
        });
    },
    findData : function(e) {
        var _this = this;
        if (!isEmpty(e)) _this = $(e.target).data("that");
        var params = _this.sysUtils.getBindDocJson(_this.bindBaseModels.bindFieldArray);
        if (!isEmpty(params["beginTime"])) params["beginTime"] = params["beginTime"].pattern("yyyy-MM-dd");
        if (!isEmpty(params["endTime"])) params["endTime"] = params["endTime"].pattern("yyyy-MM-dd");
        var dataT = {jsonParam : JSON.stringify(params)};
        var dataSource = _this.sysUtils.getDataSource({
            url : baseApiPath + 'preferential/list',
            data : dataT,
            dataType : 'odata'
        });
        var grid = _this.$parent.find('#preferential_data_list').data('kendoGrid');
        grid.setDataSource(dataSource);
    },
    checkData : function(id) {
        var _this = this;
        _this.isEdit = false;
        if ( !id || id == undefined ){
            notification({title : "操作失败", message : "请先选择需要修改哪一行数据"}, 'info')
            return;
        }
        JsonpAjax(baseApiPath + "preferential/one/" + id, undefined, "json", function(res) {
            _this.entity = res;
            _this.editWindow = _this.sysUtils.openWindow(_this.editWindow, {
                title : "查看优惠项目",
                height : "375px",
                width : "675px",
                resizable : false,
                content : "views/parkLotCenter/discountManage/preferential_edit.html"
            });
        });
    },
    createList : function() {
        var _this = this;
        var columns = [
            {
                width:30,
                headerTemplate : '<input type="checkbox" gridId="preferential_data_list" onclick="gridCheckAll(this)" />',
                template : '<input type="checkbox" name="preferentialCode" value="${preferentialCode}" />'
            },
            {
                title : '优惠项目ID',
                field : 'preferentialCode'
            },
            {
                title : '优惠项目名称',
                field : 'preferentialName'
            },
            {
                title : '优惠项目类型',
                template:'#:Utils.getModelNameByParentKey(BASIS.PREFERENTIAL_TYPE.ROOT, preferentialType)#'
            },
            {
                title : '相关商户',
                template : '${data.merchant != null ? data.merchant.merchantName : "暂无"}'
            },
            {
                title : '优惠值',
                field : 'preferentialContent'
            },
            {
                title : '优惠对象',
                template:'#:Utils.getModelNameByParentKey(BASIS.PREFERENTIAL_OBJECT.ROOT, policiesObject)#'
            },
            {
                title : '起始时间',
                field : 'beginTime'
            },
            {
                title : '截止时间',
                field : 'endTime'
            }
        ];
        _this.sysUtils.createGird(_this.$parent.find('#preferential_data_list'), {
            selectable : 'single',
            autoSync : true,
            columnMenu : true,
            pageable : {input : true, numeric : false},
            columns : columns,
            change : function(e) {
                var selected = $.map(this.select(), function(itm) {
                    return $(itm).find("input[type=checkbox]").val();
                });
                _this.selectRowId = selected[0];
            },
            dataBound:function(){
                _this.$parent.find("#preferential_data_list").find("tr:gt(0)").unbind("dblclick");
                _this.$parent.find("#preferential_data_list").find("tr:gt(0)").dblclick( function(e) {
                    var grid = _this.$parent.find("#preferential_data_list").data("kendoGrid");
                    var dataItem = grid.dataItem(grid.select());
                    //打开查看窗口
                    _this.checkData(dataItem["preferentialCode"]);
                });
            }
        });
    }
}

var PreferentialEdit = function($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
}
PreferentialEdit.prototype = {
    init : function() {
        var _this = this;
        var fieldArray = this.sysUtils.getBindFieldArray(this.$parent);
        var functionArray = [
            {fName : "save_btn", fs : this.saveInfo},
            {fName : "cancel", fs : function() { $('#'+preferentialManager.editWindow).data('kendoWindow').close(); }}
        ];
        this.bindBaseModels = new bindBaseModel(null, fieldArray, functionArray, null);
        this.sysUtils.bindDoucment(this.bindBaseModels, this.$parent, this);
        Utils.createDataDictDropDownList({div : this.$parent.find('#preferentialType'), parentModelKey : BASIS.PREFERENTIAL_TYPE.ROOT, change:function(e){
            var node = this.dataItem(this.select());
            if (!isEmpty(node.modelValue)) {
                if (node.modelValue == Utils.getModelValueByModelKey(BASIS.PREFERENTIAL_TYPE.CASH_TICKET)) {
                    _this.$parent.find('#preferentialContentCov').html(' 元');
                } else if (node.modelValue == Utils.getModelValueByModelKey(BASIS.PREFERENTIAL_TYPE.DISCOUNT)) {
                    _this.$parent.find('#preferentialContentCov').html(' 折');
                } else if (node.modelValue == Utils.getModelValueByModelKey(BASIS.PREFERENTIAL_TYPE.REDUCTION)) {
                    _this.$parent.find('#preferentialContentCov').html(' 时');
                }
            }
        }}, this);
        Utils.createDataDictDropDownList({div : this.$parent.find('#preferentialObject'), parentModelKey : BASIS.PREFERENTIAL_OBJECT.ROOT, change:function(e) {

        }}, this);
        JsonpAjax(baseApiPath + 'merchant/interface/dropdown', null, 'json', function (res) {
            var list = res;
            if (!isEmpty(list)) {
                var $m = _this.$parent.find('#merchant').kendoDropDownList({
                    dataTextField : 'merchantName',
                    dataValueField : 'id',
                    dataSource : list,
                    change : function () {
                    }
                }).data('kendoDropDownList');
                $m.select(0);
                _this.sysUtils.mvvmModel.set("merchantId",list[0]['id']);
            } else {
                list = [{'id':'-1', 'merchantName':'请先添加商家'}];
                var $m = _this.$parent.find('#merchant').kendoDropDownList({
                    dataTextField : 'merchantName',
                    dataValueField : 'id',
                    dataSource : list,
                    change : function () {
                    }
                }).data('kendoDropDownList');
                $m.select(0);
            }
        }, false);

        if (preferentialManager.entity && preferentialManager.entity != null && preferentialManager.entity != undefined) {
            this.sysUtils.setBindFieldValue(preferentialManager.entity);
            _this.sysUtils.mvvmModel.set("merchantId", preferentialManager.entity.merchant.id);
            var type = preferentialManager.entity.preferentialType;
            if (node.modelValue == Utils.getModelValueByModelKey(BASIS.PREFERENTIAL_TYPE.CASH_TICKET)) {
                _this.$parent.find('#preferentialContentCov').html(' 元');
            } else if (node.modelValue == Utils.getModelValueByModelKey(BASIS.PREFERENTIAL_TYPE.DISCOUNT)) {
                _this.$parent.find('#preferentialContentCov').html(' 折');
            } else if (node.modelValue == Utils.getModelValueByModelKey(BASIS.PREFERENTIAL_TYPE.REDUCTION)) {
                _this.$parent.find('#preferentialContentCov').html(' 时');
            }
            preferentialManager.entity = undefined;
        }
        if (false == preferentialManager.isEdit) {
            this.$parent.find("input[type]").attr("disabled","disabled");
            this.$parent.find("select").attr("disabled","disabled");
            this.$parent.find("textarea").attr("disabled","disabled");
            this.$parent.find('#preferentialType').data("kendoDropDownList").enable(false);
            this.$parent.find('#preferentialObject').data("kendoDropDownList").enable(false);
            //this.$parent.find('.save').remove();
            this.$parent.find(".basicInfo-btn").remove();
        }
    },
    saveInfo : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data('that');
        }
        if (isEmpty(_this.$parent.find('#preferentialType').val())) {
            notification({'title':'警告', 'message':'优惠类型不能为空'}, 'info');
            return;
        }
        if (isEmpty(_this.$parent.find('#preferentialObject'))) {
            notification({'title':'警告', 'message':'优惠对象不能为空'}, 'info');
            return;
        }
        if (isEmpty(_this.$parent.find('#merchant').val()) || _this.$parent.find('#merchant').val() == '-1') {
            notification({'title':'警告', 'message':'必须选择对应商家！'}, 'info');
            return;
        }
        var params = _this.sysUtils.getBindDocJson();
        var dataT = {jsonParam : JSON.stringify(params)};
        JsonpAjax(baseApiPath + "preferential/save", dataT, "json", function(res) {
            preferentialManager.findData();
            $('#' + preferentialManager.editWindow).data('kendoWindow').close();
        });
    }
}